package com.ddc.study.feature.main.project.detail;

import com.ddc.study.entity.Article;
import com.ddc.study.entity.MainData;
import com.ddc.study.net.NetworkUtil;
import com.ddc.study.net.response.BaseResponse;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created on 2018/8/18.
 *
 * @author lshun
 * @version 1.0
 */
class DetailPresenter extends DetailContract.IPresenter {
    @Override
    void loadData(@IntRange(from = 1) final int page, final int cid) {
        //TODO 数据需要缓冲
        NetworkUtil.getProjectData(page, cid).enqueue(new Callback<BaseResponse<MainData<Article>>>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<MainData<Article>>> call,
                                   @NonNull Response<BaseResponse<MainData<Article>>> response) {
                if (!isViewAttached()) return;
                if (!response.isSuccessful()) {
                    getView().loadDataFailed("请求失败(" + response.code() + ")");
                    return;
                }
                BaseResponse<MainData<Article>> body = response.body();
                if (body == null) {
                    getView().loadDataFailed("body is null");
                } else if (!body.isSuccess()) {
                    getView().loadDataFailed(body.getErrorMsg());
                } else {
                    getView().loadDataSuccess(body.getData());
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<MainData<Article>>> call,
                                  @NonNull Throwable t) {
                if (isViewAttached()) getView().loadDataFailed(t.getMessage());
            }
        });
    }
}
